package com.behome.netty.netty_B.server;

import com.behome.netty.common.ByteConventerKit;
import com.behome.netty.common.DecodeResult;
import com.behome.netty.netty_B.bean.ReBackPacket;
import com.behome.netty.netty_B.bean.ReBackPacketHead;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.util.*;

/**
 * @author bh_ljy
 * @description: 应急广播国标附录B解析器
 * @date: 2024/3/29 15:20
 */
@Slf4j
public class StandardBDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> list) {
        try {
            in.markReaderIndex();
            byte[] buffer = new byte[in.readableBytes()];
            in.readBytes(buffer);
            Map<String, byte[]> map = new HashMap<>();
            map.put("data", buffer);
            boolean rightDecoder = false;
            List<Object> obj = new ArrayList<>();
            try {
                DecodeResult decodeResult = decode(map, obj);
                if (null != decodeResult && !decodeResult.isSuccess()) {
                    rightDecoder = decodeResult.isRightDecoder();
                }
            } catch (Exception var12) {
                String msg = "对" + ctx.channel().remoteAddress().toString() + "发来的数据[" + ByteConventerKit.bytesToHexStr(buffer, false) + "]解析时发生错误.";
                log.error(msg, var12);
            }
            if (!obj.isEmpty()) {
                list.addAll(obj);
            }
            if (rightDecoder && map.containsKey("data") && map.get("data").length > 0) {
                int readerIndex = buffer.length - map.get("data").length;
                if (readerIndex >= 0) {
                    in.readerIndex(readerIndex);
                }
            }
        } catch (Exception e) {
            log.error("附录B解析异常：" + Arrays.toString(e.getStackTrace()));
            throw e;
        }
    }

    public DecodeResult decode(Map<String, byte[]> bufferMap, List<Object> returnObjs) {
        if (!bufferMap.containsKey("data")) {
            return null;
        } else {
            byte[] tmpHeadFlag = new byte[]{((byte[]) bufferMap.get("data"))[0], ((byte[]) bufferMap.get("data"))[1]};
            if (tmpHeadFlag[0] == ReBackPacketHead.FLAG[0] && tmpHeadFlag[1] == ReBackPacketHead.FLAG[1]) {
                if (bufferMap.get("data").length <= 32) {
                    return new DecodeResult(false, true);
                } else {
                    ByteBuffer byteBuffer = ByteBuffer.wrap((byte[]) bufferMap.get("data")).asReadOnlyBuffer();
                    short packetLength = byteBuffer.getShort(9);
                    if (byteBuffer.remaining() < packetLength) {
                        System.out.println("3长度不够一个包，下一周期处理");
                        return new DecodeResult(false, true);
                    } else {
                        byte[] data = new byte[packetLength];
                        byteBuffer.get(data, 0, data.length);
                        ReBackPacket packet = ReBackPacket.deserialize(data);
                        if (returnObjs == null) {
                            returnObjs = new ArrayList<>();
                        }
                        returnObjs.add(packet);
                        byte[] remainData;
                        if (byteBuffer.hasRemaining()) {
                            remainData = new byte[byteBuffer.remaining()];
                            byteBuffer.get(remainData);
                            bufferMap.put("data", remainData);
                            this.decode(bufferMap, returnObjs);
                        } else {
                            bufferMap.remove("data");
                        }

                        if (byteBuffer.hasRemaining()) {
                            remainData = new byte[byteBuffer.remaining()];
                            byteBuffer.get(remainData);
                            bufferMap.put("data", remainData);
                        } else {
                            bufferMap.remove("data");
                        }

                        return new DecodeResult(true, true);
                    }
                }
            } else {
                return new DecodeResult(false, false);
            }
        }
    }
}
